<template>
  <div class="online-exam-container">
    <div class="exam-layout">
      <!-- 考试头部 -->
      <div class="exam-header">
        <div class="exam-info">
          <h2>{{ examInfo.title }}</h2>
          <div class="exam-meta">
            <span>总分：{{ examInfo.totalScore }}分</span>
            <span>题目：{{ currentQuestionIndex + 1 }}/{{ questions.length }}</span>
          </div>
        </div>
        <div class="exam-timer">
          <div class="timer-display" :class="{ 'timer-warning': timeRemaining < 300 }">
            <el-icon><Clock /></el-icon>
            <span>{{ formatTime(timeRemaining) }}</span>
          </div>
          <el-button type="primary" @click="submitExam" :loading="submitting">
            提交试卷
          </el-button>
        </div>
      </div>

      <!-- 考试主体 -->
      <div class="exam-body">
        <!-- 题目导航 -->
        <div class="question-nav">
          <div class="nav-header">
            <h4>题目导航</h4>
            <div class="nav-legend">
              <div class="legend-item">
                <span class="legend-dot answered"></span>
                <span>已答</span>
              </div>
              <div class="legend-item">
                <span class="legend-dot current"></span>
                <span>当前</span>
              </div>
              <div class="legend-item">
                <span class="legend-dot unanswered"></span>
                <span>未答</span>
              </div>
            </div>
          </div>
          <div class="nav-grid">
            <div 
              v-for="(question, index) in questions"
              :key="question.id"
              class="nav-item"
              :class="{
                current: currentQuestionIndex === index,
                answered: isQuestionAnswered(question),
                unanswered: !isQuestionAnswered(question)
              }"
              @click="goToQuestion(index)"
            >
              {{ index + 1 }}
            </div>
          </div>
        </div>

        <!-- 题目内容 -->
        <div class="question-content">
          <div v-if="currentQuestion" class="question-container">
            <!-- 题目信息 -->
            <div class="question-header">
              <div class="question-info">
                <span class="question-type">{{ getQuestionTypeText(currentQuestion.type) }}</span>
                <span class="question-score">{{ currentQuestion.score }}分</span>
              </div>
              <div class="question-number">
                第{{ currentQuestionIndex + 1 }}题 / 共{{ questions.length }}题
              </div>
            </div>

            <!-- 题目题干 -->
            <div class="question-stem">
              <div class="question-text" v-html="currentQuestion.content"></div>
              <div v-if="currentQuestion.image" class="question-image">
                <el-image :src="currentQuestion.image" fit="contain" />
              </div>
            </div>

            <!-- 题目选项 -->
            <div class="question-options">
              <!-- 单选题 -->
              <div v-if="currentQuestion.type === 'SINGLE_CHOICE'" class="single-choice">
                <el-radio-group v-model="currentAnswer" @change="saveAnswer">
                  <el-radio 
                    v-for="option in currentQuestion.options"
                    :key="option.key"
                    :value="option.key"
                    class="option-item"
                  >
                    <span class="option-key">{{ option.key }}.</span>
                    <span class="option-text" v-html="option.text"></span>
                  </el-radio>
                </el-radio-group>
              </div>

              <!-- 多选题 -->
              <div v-else-if="currentQuestion.type === 'MULTIPLE_CHOICE'" class="multiple-choice">
                <el-checkbox-group v-model="currentAnswer" @change="saveAnswer">
                  <el-checkbox 
                    v-for="option in currentQuestion.options"
                    :key="option.key"
                    :value="option.key"
                    class="option-item"
                  >
                    <span class="option-key">{{ option.key }}.</span>
                    <span class="option-text" v-html="option.text"></span>
                  </el-checkbox>
                </el-checkbox-group>
              </div>

              <!-- 判断题 -->
              <div v-else-if="currentQuestion.type === 'TRUE_FALSE'" class="true-false">
                <el-radio-group v-model="currentAnswer" @change="saveAnswer">
                  <el-radio value="true" class="option-item">
                    <span class="option-text">正确</span>
                  </el-radio>
                  <el-radio value="false" class="option-item">
                    <span class="option-text">错误</span>
                  </el-radio>
                </el-radio-group>
              </div>

              <!-- 填空题 -->
              <div v-else-if="currentQuestion.type === 'FILL_BLANK'" class="fill-blank">
                <div 
                  v-for="(blank, index) in currentQuestion.blanks"
                  :key="index"
                  class="blank-item"
                >
                  <label>第{{ index + 1 }}空：</label>
                  <el-input 
                    v-model="currentAnswer[index]"
                    @blur="saveAnswer"
                    placeholder="请输入答案"
                  />
                </div>
              </div>

              <!-- 简答题 -->
              <div v-else-if="currentQuestion.type === 'SHORT_ANSWER'" class="short-answer">
                <el-input
                  v-model="currentAnswer"
                  type="textarea"
                  :rows="8"
                  @blur="saveAnswer"
                  placeholder="请输入您的答案..."
                />
              </div>

              <!-- 编程题 -->
              <div v-else-if="currentQuestion.type === 'CODING'" class="coding-question">
                <div class="coding-editor">
                  <div class="editor-header">
                    <span>编程语言：</span>
                    <el-select v-model="codingLanguage" @change="onLanguageChange">
                      <el-option 
                        v-for="lang in currentQuestion.supportedLanguages"
                        :key="lang"
                        :label="lang"
                        :value="lang"
                      />
                    </el-select>
                  </div>
                  <div ref="codeEditor" class="code-editor"></div>
                </div>
                <div class="coding-actions">
                  <el-button @click="runCode" :loading="running">运行代码</el-button>
                  <el-button @click="submitCode">提交代码</el-button>
                </div>
                <div v-if="codeOutput" class="code-output">
                  <h4>运行结果：</h4>
                  <pre>{{ codeOutput }}</pre>
                </div>
              </div>
            </div>

            <!-- 题目导航按钮 -->
            <div class="question-nav-buttons">
              <el-button 
                @click="previousQuestion" 
                :disabled="currentQuestionIndex === 0"
              >
                <el-icon><ArrowLeft /></el-icon>
                上一题
              </el-button>
              <el-button 
                @click="nextQuestion"
                :disabled="currentQuestionIndex === questions.length - 1"
              >
                下一题
                <el-icon><ArrowRight /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 提交确认对话框 -->
    <el-dialog v-model="showSubmitDialog" title="提交试卷" width="500px">
      <div class="submit-summary">
        <h4>答题情况统计</h4>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="总题数">{{ questions.length }}</el-descriptions-item>
          <el-descriptions-item label="已答题数">{{ answeredCount }}</el-descriptions-item>
          <el-descriptions-item label="未答题数">{{ unansweredCount }}</el-descriptions-item>
          <el-descriptions-item label="剩余时间">{{ formatTime(timeRemaining) }}</el-descriptions-item>
        </el-descriptions>
        <div v-if="unansweredCount > 0" class="warning-text">
          <el-icon><Warning /></el-icon>
          还有{{ unansweredCount }}道题未作答，确定要提交吗？
        </div>
      </div>
      <template #footer>
        <el-button @click="showSubmitDialog = false">继续答题</el-button>
        <el-button type="primary" @click="confirmSubmit" :loading="submitting">
          确认提交
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, onUnmounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getExamQuestions,
  saveExamAnswer,
  submitExamPaper,
  runExamCode
} from '@/api/exam'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(true)
const submitting = ref(false)
const running = ref(false)
const showSubmitDialog = ref(false)
const examInfo = ref({})
const questions = ref([])
const answers = ref({})
const currentQuestionIndex = ref(0)
const currentAnswer = ref(null)
const codingLanguage = ref('javascript')
const codeOutput = ref('')
const codeEditor = ref()
const timeRemaining = ref(0)
const timer = ref(null)

// 计算属性
const currentQuestion = computed(() => {
  return questions.value[currentQuestionIndex.value]
})

const answeredCount = computed(() => {
  return Object.keys(answers.value).length
})

const unansweredCount = computed(() => {
  return questions.value.length - answeredCount.value
})

// 获取考试题目
const loadExamQuestions = async () => {
  try {
    const response = await getExamQuestions(route.params.recordId)
    if (response.code === 200) {
      examInfo.value = response.data.examInfo
      questions.value = response.data.questions
      answers.value = response.data.answers || {}
      timeRemaining.value = response.data.timeRemaining
      
      // 加载当前题目答案
      loadCurrentAnswer()
      
      // 启动计时器
      startTimer()
    }
  } catch (error) {
    console.error('获取考试题目失败:', error)
    ElMessage.error('获取考试题目失败')
  }
}

// 加载当前题目答案
const loadCurrentAnswer = () => {
  if (!currentQuestion.value) return
  
  const questionId = currentQuestion.value.id
  if (answers.value[questionId]) {
    currentAnswer.value = answers.value[questionId]
  } else {
    // 初始化答案
    if (currentQuestion.value.type === 'MULTIPLE_CHOICE') {
      currentAnswer.value = []
    } else if (currentQuestion.value.type === 'FILL_BLANK') {
      currentAnswer.value = new Array(currentQuestion.value.blanks.length).fill('')
    } else {
      currentAnswer.value = ''
    }
  }
}

// 保存答案
const saveAnswer = async () => {
  if (!currentQuestion.value) return
  
  const questionId = currentQuestion.value.id
  answers.value[questionId] = currentAnswer.value
  
  try {
    await saveExamAnswer(route.params.recordId, {
      questionId,
      answer: currentAnswer.value
    })
  } catch (error) {
    console.error('保存答案失败:', error)
  }
}

// 跳转到指定题目
const goToQuestion = (index) => {
  if (index >= 0 && index < questions.value.length) {
    currentQuestionIndex.value = index
    loadCurrentAnswer()
  }
}

// 上一题
const previousQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    goToQuestion(currentQuestionIndex.value - 1)
  }
}

// 下一题
const nextQuestion = () => {
  if (currentQuestionIndex.value < questions.value.length - 1) {
    goToQuestion(currentQuestionIndex.value + 1)
  }
}

// 判断题目是否已答
const isQuestionAnswered = (question) => {
  return answers.value.hasOwnProperty(question.id)
}

// 提交试卷
const submitExam = () => {
  showSubmitDialog.value = true
}

// 确认提交
const confirmSubmit = async () => {
  submitting.value = true
  try {
    const response = await submitExamPaper(route.params.recordId, {
      answers: answers.value
    })
    if (response.code === 200) {
      ElMessage.success('试卷提交成功')
      router.push(`/exam/${route.params.examId}/result/${route.params.recordId}`)
    }
  } catch (error) {
    console.error('提交试卷失败:', error)
    ElMessage.error('提交试卷失败')
  } finally {
    submitting.value = false
    showSubmitDialog.value = false
  }
}

// 运行代码
const runCode = async () => {
  if (!currentAnswer.value) {
    ElMessage.warning('请先输入代码')
    return
  }
  
  running.value = true
  try {
    const response = await runExamCode({
      code: currentAnswer.value,
      language: codingLanguage.value,
      questionId: currentQuestion.value.id
    })
    if (response.code === 200) {
      codeOutput.value = response.data.output
    }
  } catch (error) {
    console.error('运行代码失败:', error)
    ElMessage.error('运行代码失败')
  } finally {
    running.value = false
  }
}

// 提交代码
const submitCode = () => {
  saveAnswer()
  ElMessage.success('代码已保存')
}

// 语言切换
const onLanguageChange = () => {
  // 重新初始化编辑器
  initCodeEditor()
}

// 初始化代码编辑器
const initCodeEditor = async () => {
  await nextTick()
  // 这里可以集成代码编辑器，如 Monaco Editor、CodeMirror 等
  // 示例代码，实际需要根据选择的编辑器进行配置
}

// 启动计时器
const startTimer = () => {
  timer.value = setInterval(() => {
    timeRemaining.value -= 1000
    if (timeRemaining.value <= 0) {
      // 时间到，自动提交
      autoSubmit()
    }
  }, 1000)
}

// 自动提交
const autoSubmit = async () => {
  clearInterval(timer.value)
  ElMessage.warning('考试时间已到，系统将自动提交试卷')
  
  try {
    await submitExamPaper(route.params.recordId, {
      answers: answers.value,
      autoSubmit: true
    })
    router.push(`/exam/${route.params.examId}/result/${route.params.recordId}`)
  } catch (error) {
    console.error('自动提交失败:', error)
  }
}

// 工具函数
const getQuestionTypeText = (type) => {
  const typeMap = {
    'SINGLE_CHOICE': '单选题',
    'MULTIPLE_CHOICE': '多选题',
    'TRUE_FALSE': '判断题',
    'FILL_BLANK': '填空题',
    'SHORT_ANSWER': '简答题',
    'CODING': '编程题'
  }
  return typeMap[type] || type
}

const formatTime = (milliseconds) => {
  if (milliseconds <= 0) return '00:00:00'
  
  const hours = Math.floor(milliseconds / (1000 * 60 * 60))
  const minutes = Math.floor((milliseconds % (1000 * 60 * 60)) / (1000 * 60))
  const seconds = Math.floor((milliseconds % (1000 * 60)) / 1000)
  
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

// 页面加载
onMounted(async () => {
  loading.value = true
  try {
    await loadExamQuestions()
    await initCodeEditor()
  } finally {
    loading.value = false
  }
})

// 页面卸载
onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value)
  }
})

// 监听页面离开
window.addEventListener('beforeunload', (event) => {
  event.preventDefault()
  event.returnValue = '确定要离开考试页面吗？'
})
</script>

<style lang="scss" scoped>
.online-exam-container {
  height: 100vh;
  overflow: hidden;
  background: #f5f5f5;
}

.exam-layout {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.exam-header {
  background: white;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .exam-info {
    h2 {
      margin: 0 0 8px 0;
      font-size: 20px;
    }
    
    .exam-meta {
      display: flex;
      gap: 16px;
      color: #909399;
      font-size: 14px;
    }
  }
  
  .exam-timer {
    display: flex;
    align-items: center;
    gap: 16px;
    
    .timer-display {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 18px;
      font-weight: 600;
      color: #409eff;
      
      &.timer-warning {
        color: #f56c6c;
      }
    }
  }
}

.exam-body {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.question-nav {
  width: 250px;
  background: white;
  border-right: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
  
  .nav-header {
    padding: 16px;
    border-bottom: 1px solid #ebeef5;
    
    h4 {
      margin: 0 0 12px 0;
    }
    
    .nav-legend {
      display: flex;
      gap: 12px;
      
      .legend-item {
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 12px;
        
        .legend-dot {
          width: 12px;
          height: 12px;
          border-radius: 50%;
          
          &.answered {
            background: #67c23a;
          }
          
          &.current {
            background: #409eff;
          }
          
          &.unanswered {
            background: #dcdfe6;
          }
        }
      }
    }
  }
  
  .nav-grid {
    flex: 1;
    padding: 16px;
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 8px;
    overflow-y: auto;
    
    .nav-item {
      width: 32px;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 4px;
      cursor: pointer;
      font-size: 12px;
      font-weight: 600;
      
      &.answered {
        background: #67c23a;
        color: white;
      }
      
      &.current {
        background: #409eff;
        color: white;
      }
      
      &.unanswered {
        background: #f0f0f0;
        color: #909399;
        
        &:hover {
          background: #e0e0e0;
        }
      }
    }
  }
}

.question-content {
  flex: 1;
  overflow-y: auto;
  background: white;
  
  .question-container {
    padding: 24px;
    max-width: 800px;
    margin: 0 auto;
  }
  
  .question-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .question-info {
      display: flex;
      gap: 12px;
      
      .question-type {
        background: #409eff;
        color: white;
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 12px;
      }
      
      .question-score {
        background: #f56c6c;
        color: white;
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 12px;
      }
    }
    
    .question-number {
      color: #909399;
      font-size: 14px;
    }
  }
  
  .question-stem {
    margin-bottom: 24px;
    
    .question-text {
      font-size: 16px;
      line-height: 1.8;
      margin-bottom: 16px;
    }
    
    .question-image {
      text-align: center;
      
      .el-image {
        max-width: 100%;
        max-height: 300px;
      }
    }
  }
  
  .question-options {
    margin-bottom: 32px;
    
    .option-item {
      display: flex;
      align-items: flex-start;
      margin-bottom: 12px;
      padding: 12px;
      border: 1px solid #ebeef5;
      border-radius: 8px;
      cursor: pointer;
      
      &:hover {
        background: #f8f9fa;
      }
      
      .option-key {
        font-weight: 600;
        margin-right: 8px;
        flex-shrink: 0;
      }
      
      .option-text {
        flex: 1;
        line-height: 1.6;
      }
    }
    
    .blank-item {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 16px;
      
      label {
        font-weight: 600;
        min-width: 80px;
      }
      
      .el-input {
        flex: 1;
        max-width: 300px;
      }
    }
    
    .coding-question {
      .coding-editor {
        border: 1px solid #ebeef5;
        border-radius: 8px;
        overflow: hidden;
        margin-bottom: 16px;
        
        .editor-header {
          padding: 12px;
          background: #f8f9fa;
          border-bottom: 1px solid #ebeef5;
          display: flex;
          align-items: center;
          gap: 8px;
        }
        
        .code-editor {
          height: 300px;
          font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
        }
      }
      
      .coding-actions {
        margin-bottom: 16px;
        display: flex;
        gap: 8px;
      }
      
      .code-output {
        background: #f8f9fa;
        border: 1px solid #ebeef5;
        border-radius: 8px;
        padding: 16px;
        
        h4 {
          margin: 0 0 12px 0;
        }
        
        pre {
          margin: 0;
          white-space: pre-wrap;
          font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
        }
      }
    }
  }
  
  .question-nav-buttons {
    display: flex;
    justify-content: space-between;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;
  }
}

.submit-summary {
  .warning-text {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #f56c6c;
    margin-top: 16px;
    padding: 12px;
    background: #fef0f0;
    border-radius: 4px;
  }
}

@media (max-width: 768px) {
  .exam-header {
    flex-direction: column;
    gap: 12px;
  }
  
  .question-nav {
    width: 200px;
  }
  
  .nav-grid {
    grid-template-columns: repeat(4, 1fr) !important;
  }
}
</style>
